#enconding=utf-8
import os
from common.kubenetes.k8sNew import KubeClient
from common.prometheus.prometheus import PrometheusClient
from common.pai_job.task import TaskClient
import yaml


class Singleton(type):
    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__call__(*args, **kwargs)

        return cls._instance


class ClusterPrometheusClient:
    def __init__(self, prometheus_config: dict):
        self.prometheus_config = prometheus_config
        self.prometheus_client = PrometheusClient(prometheus_config['prometheus_server_url'])

    def query_range(self, exp_name: str, start_time: int, end_time: int, step: int) -> dict:
         return self.raw_query_range(exp_name, start_time, end_time, step)

    def query(self, exp_name: str) -> dict:
        return self.raw_query(exp_name)

    def raw_query_range(self, query_exp: str, start_time: int, end_time: int, step: int) -> dict:
        return self.prometheus_client.query_range(query_exp, start_time, end_time, step)

    def raw_query(self, query_exp: str) -> dict:
        return self.prometheus_client.query(query_exp)

# 设置集群信息
class ClusterClient(metaclass=Singleton):
    def __init__(self):
        master_url = os.getenv("MASTER_URL", "")

        pyfile_dir = os.path.dirname(os.path.abspath(__file__))
        # default_config = os.path.join(pyfile_dir, "kube_config")
        kube_config = os.getenv("KUBECONFIG", "")
        self.kube_client = KubeClient(master_url, kube_config)

        self.cluster_config = self.load_cluster_config()
        """
        content in config file as follow 
        prometheus:
          prometheus_server_url: http://*****
        """
        prometheus_config = self.get_prometheus_config()
        self.prometheus_client = ClusterPrometheusClient(prometheus_config)

        """
        content in config file as follow 
        task:
          rest_server_url: http://****
          token:
            username: ***
            password: ***
        """
        task_config = self.get_task_config()
        self.task_client = TaskClient(task_config["rest_server_url"], task_config["token"])

    def load_cluster_config(self):
        pyfile_dir = os.path.dirname(os.path.abspath(__file__))
        default_config = os.path.join(pyfile_dir, "cluster_config.yaml")
        cluster_config_path = os.getenv("CLUSTER_CONFIG", default_config)
        if not cluster_config_path:
            raise Exception("env CLUSTER_CONFIG is not set")

        with open(cluster_config_path) as fd:
            cluster_config = yaml.load(fd)
        return cluster_config

    def get_prometheus_config(self):
        return self.cluster_config["prometheus"]

    def get_task_config(self):
        return self.cluster_config["task"]


cluster_client = ClusterClient()




